package com.example.routeplansystem.intercepter;

import com.example.routeplansystem.anotation.AllowAccess;
import com.example.routeplansystem.anotation.UserPermissionConf;
import com.example.routeplansystem.anotation.UserPermissionType;
import com.example.routeplansystem.constant.SessionMessage;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author LuCong
 * @since 2020-12-08
 **/
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            if (handler instanceof ResourceHttpRequestHandler) {
                // 静态资源bug
                return true;
            }
            return false;
        }
        //获取handlerMethod以拿到注解
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        AllowAccess allowAccess = handlerMethod.getMethodAnnotation(AllowAccess.class);

        //获取类上是否有需要权限验证的注解
        UserPermissionConf userPermissionConf = handlerMethod.getBeanType().getAnnotation(UserPermissionConf.class);
        if (userPermissionConf == null) {
            // 放行,没有注解也无法从request中获取userId
            return true;
        }

        Object UserIdAttribute = request.getSession().getAttribute(SessionMessage.USER_ID_KEY);
        if (UserIdAttribute == null) {
            // todo 是否需要对Session中的userId作校验
            if (allowAccess != null) {
                //有直接访问注解,放行
                return true;
            }
            if (userPermissionConf.Type().equals(UserPermissionType.ALLOW)) {
                // 放行
                return true;
            }
            setRespError(response, HttpStatus.UNAUTHORIZED.value(), "用户未登录!!!");
        }
        Integer userId = null;
        try {
            userId = Integer.parseInt(UserIdAttribute.toString());
        } catch (NumberFormatException e) {
            setRespError(response, HttpStatus.UNAUTHORIZED.value(), "用户未登录!!!");
        }

        // 将用户信息放进request中
        // 使用@RequestAttribute接收
        request.setAttribute("userId", userId);

        return true;
    }


    public void setRespError(HttpServletResponse response, int code, String msg) {
        try {
            response.sendError(code, msg);
        } catch (Exception e) {

        }

    }

}
